import React, { useRef,useState } from 'react'
import MemoTable from '@/components/MemoTable'
import {Button, Space,Modal,message,Table,Input,Tooltip} from 'antd'
import {useTranslation} from 'react-i18next'
import { ProFormColumnsType } from '@ant-design/pro-components'
import { EditOutlined, DeleteOutlined,PlusOutlined,DownloadOutlined } from '@ant-design/icons'; 
import { productLists,productallLists,delProduct,deltsProduct,recoverProduct,getProductFileList,mergeINCIRiskList,updateReport,exportPlm,importInciRiskJh} from "@/api/modules/report";
import { render } from 'react-dom'
import { useNavigate } from 'react-router-dom'
import useCacheAlive from '@/hooks/useCacheAlive';

const Sa = () => {
  const { t } = useTranslation();
  const table = useRef(null)
  const navigate = useNavigate()
  const [onReloadNum,setOnReloadNum] = useState(null)
  const [columnsdata, setColumns] = useState([]);  
  const [data, setData] = useState([]);  
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [ingredientsModalVisible, setIngredientsModalVisible] = useState(false);  
  const [checkButtonDisabled, setCheckButtonDisabled] = useState(true);  
  const [inciInput, setInciInput] = useState(''); 
  const [resultsModalVisible, setResultsModalVisible] = useState(false);  
  const [resultsData, setResultsData] = useState([]); // 用于存储查询结果的数据  
  const [resultsColumns, setResultsColumn] = useState([]); // 用于存储查询结果的数据  
  const [visData,setVisData] = useState(false)

  const formColumns:ProFormColumnsType[] = [{
    title: t('inputKeyValue'),
    dataIndex: 'search',
    valueType: 'text', 

  }]
  
     // 显示Modal  
  const showIngredientsModal = () => { 
      setIngredientsModalVisible(true);  
    };  
    
  const showAllData = () =>{
    setVisData(true)
    setOnReloadNum(Date.now())
  }

  const showNoAllData = () =>{
    setVisData(false)
    setOnReloadNum(Date.now())
  }


  const handleADDReport = ()=>{
    // const [step2formValues, setFormValues] =  useCacheAlive({}, `table-addreport-step2formValues`) 
    // const [step2Table, setStep2Table] =useCacheAlive([], `table-addreport-step2Table`)
    // const [step3formValues, setStep3FormValues] = useCacheAlive({}, `table-addreport-step3formValues`)
    // const [step4formValues, setStep4FormValues] =  useCacheAlive({}, `table-addreport-step4formValues`)
    // const [step5formValues, setStep5FormValues] = useCacheAlive({}, `table-addreport-step5formValues`)
    // const [safety_product_id, setSafety_product_id] = useCacheAlive({}, `table-addreport-safety_product_id`)
    // const [report_id, setReport_id] = useCacheAlive(0, `table-addreport-report_id`)
    // setStorage( `table-addreport-current`)
    // setStorage( `table-addreport-step1Value`)
    // setStorage( `table-addreport-safety_product_id`)
    // remove('table-addreport-current');
    // remove('table-addreport-step1Value');
    // remove('table-addreport-safety_product_id')
    navigate('/sa/addreport')
  }

  const renderOperator = <Space wrap>
    <Button type="primary" onClick={handleADDReport}>{t('report.addreport')}</Button>
    {/* <Button>{t('report.addreportByPLM')}</Button> */}
    {/* <Button>{t('report.checkreport')}</Button> */}
    {/* <Button>{t('report.import')}</Button> */}
    <Button type="primary"  onClick={showIngredientsModal}>{t('report.ingredientsRiskSubstance')}</Button>
     <Button type="primary"  onClick={showAllData}>{t('allData')}</Button>
     <Button type="primary"  onClick={showNoAllData}>{t('nonInvisibleData')}</Button>
  </Space>

  const columns = [
    {
      title: t('report.id'),
      dataIndex: 'id',
      key: 'id',
      width: 50,
      fixed: 'left',
      render: (id,record) => {
        // 假设你有一个函数或逻辑来判断ownerAddress是否应该显示为灰色并带有删除线  
        const isGrayedOut = record.productStatus === 'Invisible'; // 或者其他逻辑  
     
        // 设置样式  
        const style = isGrayedOut ? {  
          color: 'gray', // 灰色文本  
          textDecoration: 'line-through', // 删除线  
        } : {}; // 默认样式为空对象  
      
        return (  
          <Tooltip placement="topLeft" title={id}>  
            <span style={style}>{id}</span>  
          </Tooltip>  
        ); 
     }
    },
    {
      title: t('report.productCode'),
      dataIndex: 'productCode',
      key: 'productCode',
      width: 140,
      fixed: 'left',
      ellipsis: {
        showTitle: false,
      },
      render: (productCode,record) => {
        // 假设你有一个函数或逻辑来判断ownerAddress是否应该显示为灰色并带有删除线  
        const isGrayedOut = record.productStatus === 'Invisible'; // 或者其他逻辑  
     
        // 设置样式  
        const style = isGrayedOut ? {  
          color: 'gray', // 灰色文本  
          textDecoration: 'line-through', // 删除线  
        } : {}; // 默认样式为空对象  
      
        return (  
          <Tooltip placement="topLeft" title={productCode}>  
            <span style={style}>{productCode}</span>  
          </Tooltip>  
        ); 
     }
    },
    {
      title: t('report.standardCode'),
      dataIndex: 'standardCode',
      key: 'standardCode',
      width: 120,
      ellipsis: {
        showTitle: false,
      },
      render: (standardCode,record) => {
        // 假设你有一个函数或逻辑来判断ownerAddress是否应该显示为灰色并带有删除线  
        const isGrayedOut = record.productStatus === 'Invisible'; // 或者其他逻辑  
     
        // 设置样式  
        const style = isGrayedOut ? {  
          color: 'gray', // 灰色文本  
          textDecoration: 'line-through', // 删除线  
        } : {}; // 默认样式为空对象  
      
        return (  
          <Tooltip placement="topLeft" title={standardCode}>  
            <span style={style}>{standardCode}</span>  
          </Tooltip>  
        ); 
     }
    },
    {
      title: t('report.productStandardNo'),
      dataIndex: 'productStandardNo',
      key: 'productStandardNo',
      width: 170,
      ellipsis: {
        showTitle: false,
      },
      render: (productStandardNo,record) => {
        // 假设你有一个函数或逻辑来判断ownerAddress是否应该显示为灰色并带有删除线  
        const isGrayedOut = record.productStatus === 'Invisible'; // 或者其他逻辑  
     
        // 设置样式  
        const style = isGrayedOut ? {  
          color: 'gray', // 灰色文本  
          textDecoration: 'line-through', // 删除线  
        } : {}; // 默认样式为空对象  
      
        return (  
          <Tooltip placement="topLeft" title={productStandardNo}>  
            <span style={style}>{productStandardNo}</span>  
          </Tooltip>  
        ); 
     }
    },
    {
      title: t('status'),
      dataIndex: 'productStatus',
      key: 'productStatus',
      width: 160,
      render: (_, record) => {
        const isGrayedOut = record.productStatus === 'Invisible'; // 或者其他逻辑  
     
        // 设置样式  
        const style = isGrayedOut ? {  
          color: 'gray', // 灰色文本  
          textDecoration: 'line-through', // 删除线  
        } : {}; // 默认样式为空对象  
          let text = ""
          if(record.productStatus == 'NoApproval'){
            text = '未从工作流启动的安评'
          }else if(record.productStatus == 'ApprovalComplete'){
            text = '审批通过-安评未进行'
          }else if(record.productStatus == 'generating'){
            text = '进行中'
          }else if(record.productStatus == 'generated'){
            text = '已经生成报告'
          }else if(record.productStatus == 'sendOut'){
            text = '已经发送合规'
          }else if(record.productStatus == 'Invisible'){
            text = '已删除'
          }
        return (<>
            <span style={style}>{text}</span>
        </>)
      }
    },
    {
      title: t('report.fileStatus'),
      dataIndex: 'status',
      key: 'status',
      width: 160,
      ellipsis: {
        showTitle: false,
      },
      render: (status,record) => {
        // 假设你有一个函数或逻辑来判断ownerAddress是否应该显示为灰色并带有删除线  
        const isGrayedOut = record.productStatus === 'Invisible'; // 或者其他逻辑  
     
        // 设置样式  
        const style = isGrayedOut ? {  
          color: 'gray', // 灰色文本  
          textDecoration: 'line-through', // 删除线  
        } : {}; // 默认样式为空对象  
      
        return (  
          <Tooltip placement="topLeft" title={status}>  
            <span style={style}>{status}</span>  
          </Tooltip>  
        ); 
     }
    },
    {
      title: t('report.nameCn'),
      dataIndex: 'nameCn',
      key: 'nameCn',
      width: 190,
      ellipsis: {
        showTitle: false,
      },
      render: (nameCn,record) => {
        // 假设你有一个函数或逻辑来判断ownerAddress是否应该显示为灰色并带有删除线  
        const isGrayedOut = record.productStatus === 'Invisible'; // 或者其他逻辑  
     
        // 设置样式  
        const style = isGrayedOut ? {  
          color: 'gray', // 灰色文本  
          textDecoration: 'line-through', // 删除线  
        } : {}; // 默认样式为空对象  
      
        return (  
          <Tooltip placement="topLeft" title={nameCn}>  
            <span style={style}>{nameCn}</span>  
          </Tooltip>  
        ); 
     }
    },
    {
      title: t('report.nameEn'),
      dataIndex: 'nameEn',
      key: 'nameEn',
      width: 190,
      ellipsis: {
        showTitle: false,
      },
      render: (nameEn,record) => {
        // 假设你有一个函数或逻辑来判断ownerAddress是否应该显示为灰色并带有删除线  
        const isGrayedOut = record.productStatus === 'Invisible'; // 或者其他逻辑  
     
        // 设置样式  
        const style = isGrayedOut ? {  
          color: 'gray', // 灰色文本  
          textDecoration: 'line-through', // 删除线  
        } : {}; // 默认样式为空对象  
      
        return (  
          <Tooltip placement="topLeft" title={nameEn}>  
            <span style={style}>{nameEn}</span>  
          </Tooltip>  
        ); 
     }
    },
    {
      title: t('report.ownerName'),
      dataIndex: 'ownerName',
      key: 'ownerName',
      width: 150,
      ellipsis: {
        showTitle: false,
      },
      render: (ownerName,record) => {
        // 假设你有一个函数或逻辑来判断ownerAddress是否应该显示为灰色并带有删除线  
        const isGrayedOut = record.productStatus === 'Invisible'; // 或者其他逻辑  
     
        // 设置样式  
        const style = isGrayedOut ? {  
          color: 'gray', // 灰色文本  
          textDecoration: 'line-through', // 删除线  
        } : {}; // 默认样式为空对象  
      
        return (  
          <Tooltip placement="topLeft" title={ownerName}>  
            <span style={style}>{ownerName}</span>  
          </Tooltip>  
        ); 
     }
    },
    {  
      title: t('report.ownerAddress'),  
      dataIndex: 'ownerAddress',  
      key: 'ownerAddress',  
      width: 150,  
      ellipsis: {  
        showTitle: false,  
      },  
      render: (ownerAddress, record) => {  
        // 假设你有一个函数或逻辑来判断ownerAddress是否应该显示为灰色并带有删除线  
        const isGrayedOut = record.productStatus === 'Invisible'; // 或者其他逻辑  
      
        // 设置样式  
        const style = isGrayedOut ? {  
          color: 'gray', // 灰色文本  
          textDecoration: 'line-through', // 删除线  
        } : {}; // 默认样式为空对象  
      
        return (  
          <Tooltip placement="topLeft" title={ownerAddress}>  
            <span style={style}>{ownerAddress}</span>  
          </Tooltip>  
        );  
      },  
    },
    {
      title: t('report.appraiseCompany'),
      dataIndex: 'appraiseCompany',
      key: 'appraiseCompany',
      width: 160,
      ellipsis: {
        showTitle: false,
      },
      render: (appraiseCompany,record) => {
         // 假设你有一个函数或逻辑来判断ownerAddress是否应该显示为灰色并带有删除线  
         const isGrayedOut = record.productStatus === 'Invisible'; // 或者其他逻辑  
      
         // 设置样式  
         const style = isGrayedOut ? {  
           color: 'gray', // 灰色文本  
           textDecoration: 'line-through', // 删除线  
         } : {}; // 默认样式为空对象  
       
         return (  
           <Tooltip placement="topLeft" title={appraiseCompany}>  
             <span style={style}>{appraiseCompany}</span>  
           </Tooltip>  
         ); 
      }
    },
    {
      title: t('updateTime'),
      dataIndex: 'updateTime',
      key: 'updateTime',
      ellipsis: {
        showTitle: false,
      },
      render: (updateTime,record) => {
        // 假设你有一个函数或逻辑来判断ownerAddress是否应该显示为灰色并带有删除线  
        const isGrayedOut = record.productStatus === 'Invisible'; // 或者其他逻辑  
     
        // 设置样式  
        const style = isGrayedOut ? {  
          color: 'gray', // 灰色文本  
          textDecoration: 'line-through', // 删除线  
        } : {}; // 默认样式为空对象  
      
        return (  
          <Tooltip placement="topLeft" title={updateTime}>  
            <span style={style}>{updateTime}</span>  
          </Tooltip>  
        ); 
     }
    },
    {
      title: t('action'),
      width: 120,
      fixed: 'right',
      render: (_, record) => {
        const handleEdit = () => {  
          // 在这里处理编辑逻辑，使用record来获取当前行的数据  
          console.log('编辑当前行数据：', record);
          const id = record.id;  
          // 跳转到'/sa/addreport'路径，并带上id参数  
          navigate(`/sa/addreport?productId=${id}`); 
        };  
        return (<>
          <Button type="link" onClick={handleEdit}>  
           {t('edit')}  
          </Button>  
          {/* 使用三元运算符来判断显示哪个按钮 */}  
          {record.productStatus === 'Invisible' ? (  
            <Button type="link" danger onClick={() => handleRecover(record.id)}>  
              {t('recover')}  
            </Button>  
          ) : (  
            <Button type="link" danger onClick={() => handleDelete(record.id)}>  
              {t('delete')}  
            </Button>  
          )}  
          <Button type="link"  onClick={() => handleRisk(record.id)}>  
            {t('report.riskSubstance')} 
          </Button> 
        </>)
      }
    },

  ];


  // 隐藏Modal  
  const handleIngredientsModalCancel = () => {  
    setIngredientsModalVisible(false);  
    setInciInput(''); // 清空输入框  
    setCheckButtonDisabled(true); // 禁用检查结果按钮  
  };  

   // 检查按钮点击事件  
   const handleCheckIngredients = () => {  
    if (inciInput.trim()) {  
      // 这里可以添加逻辑来处理inciInput中的值，例如发送到后端等  
      // 这里只是简单演示，直接显示消息并关闭Modal  
      message.success('检查结果已处理');  
      let form = [];
      inciInput.split("\n").map((item) => {
         form.push(item)
      })
      importInciRiskJh(form).then(res=>{
        const headerData = res.data.data.header
        const columnData = res.data.data.data
           // 设置表头  
        setResultsColumn(headerData.map((title, index) => ({  
          title,  
          dataIndex: `column${index}`, // 为每个列设置一个唯一的dataIndex  
          key: `column-${index}`, // 确保key是唯一的  
          width: 140,
        })));  
      
        // 将二维数组转换为对象数组  
        const transformedData = columnData.map((row, rowIndex) => {  
          const obj = {};  
          row.forEach((value, colIndex) => {  
            obj[`column${colIndex}`] = value; // 使用dataIndex作为属性名  
          });  
          return obj;  
        });  
      
        setResultsData(transformedData);  
        setIngredientsModalVisible(false); // 关闭当前Modal  
        setInciInput(''); // 清空输入框  
        setCheckButtonDisabled(true); // 禁用检查结果按钮  
        setResultsModalVisible(true); // 打开新的Modal   
        // 如果需要打开新Modal，可以在这里调用相应的函数  
      })
   
    } else {  
      message.error('请输入INCI信息');  
    }  
  };  
  const handleResultsModalCancel = () => {  
    setResultsModalVisible(false);  
  };  

    // 渲染新的 modal（用于显示查询结果）  
    const resultsModal = (  
      <Modal  
        title="Risk Substance"  
        visible={resultsModalVisible}  
        onCancel={handleResultsModalCancel}  
        footer={null}  
        width={800}
      >  
        <Table  dataSource={resultsData} columns={resultsColumns}  pagination={false}/>  
      </Modal>  
    );  

    // 输入框内容变化时更新状态  
    const handleInciInputChange = (e) => {  
      const value = e.target.value;  
      setInciInput(value);  
      setCheckButtonDisabled(!value.trim()); // 当输入框有内容时启用按钮  
    };  
    

    // Modal内容  
  const modalContent = (  
    <div>  
      <Button  
        type="primary"  
        size="small"  
        onClick={handleCheckIngredients}  
        disabled={checkButtonDisabled}  
      >  
        {t('viewResult')}  
      </Button>  
      <p style={{ marginTop: '16px' }}>{'INCI'}</p>  
      <Input.TextArea  
        placeholder={'请输入INCI,多个请务必换行,可从EXCEL复制粘贴,Please input Inci，multiple entries must be in different lines. Copy & Paste are supported. '}  
        rows={4}  
        value={inciInput}  
        onChange={handleInciInputChange}  
      />  
    </div>  
  );  
  

  const handleRisk = (id) =>{
    mergeINCIRiskList(id).then(res=>{
      console.log(res,'peifangfengxian')
      if(res.data.data==null){
        message.error("No Data, please check")
      }else{
        const headerData = res.data.data.header
        const columnData = res.data.data.data

       // 设置表头  
        setColumns(headerData.map((title, index) => ({  
          title,  
          dataIndex: `column${index}`, // 为每个列设置一个唯一的dataIndex  
          key: `column-${index}`, // 确保key是唯一的  
          width: 140,
        })));  
      
        // 将二维数组转换为对象数组  
        const transformedData = columnData.map((row, rowIndex) => {  
          const obj = {};  
          row.forEach((value, colIndex) => {  
            obj[`column${colIndex}`] = value; // 使用dataIndex作为属性名  
          });  
          return obj;  
        });  
      
        setData(transformedData);  
        setIsModalVisible(true);  
      }
   })
  }
  const handleOk = () => {  
    setIsModalVisible(false);  
  };  
  
  const handleCancel = () => {  
    setIsModalVisible(false);  
  };  

  const handleDelete = (id) =>{
    let Inciids = [];
    Inciids.push(id)
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: t('tsDeleteWord'), 
      onOk() {  
        deltsProduct(Inciids).then(res=>{
            message.success("Success")
            setOnReloadNum(Date.now())
        }) 
      },  
    }); 
  }

  const handleRecover = (id) =>{
    let Inciids = [];
    Inciids.push(id)
    recoverProduct(Inciids).then(res=>{
      message.success("Success")
      setOnReloadNum(Date.now())
  }) 
  }

  const getData = async (formData) => {
    formData.orderby = 'update_time'
    formData.order = 0
    if(visData==false){
      const {data, success} = await productLists(formData)
      if(!success) return false
      return {
        data: data.data?.page || [],
        total: data.data?.total
      }
    }else{
      const {data, success} = await productallLists(formData)
      if(!success) return false
      return {
        data: data.data?.page || [],
        total: data.data?.total
      }
    }
 
  }
  return (
    <div>
    <MemoTable 
      onSelector={({keys, rows}) => {}}
      name='basic'
      hasSeletor={false}
      formColumns={formColumns}
      columns={columns as any}
      rowKey='id'
      operator={renderOperator}
      getData={getData}
      refreshKey={onReloadNum}
    />
      <Modal  
        title="Risk Substance"  
        visible={isModalVisible}  
        onOk={handleOk}  
        onCancel={handleCancel}  
        footer={null} 
        width={1000} // 设置Modal的宽度 
      >  
        <Table  
          bordered
          columns={columnsdata}  
          dataSource={data} // 注意：这里的数据源格式可能并不适合直接使用，需要根据实际情况调整  
          pagination={false} // 如果数据不多，可以关闭分页  
        />  
      </Modal>  
      <Modal  
        title={"INCI"}  
        visible={ingredientsModalVisible}  
        onOk={handleCheckIngredients}  
        onCancel={handleIngredientsModalCancel}  
        footer={null}  
      >  
        {modalContent}  
      </Modal>  
      {resultsModal}  
    </div>
    
  )
}
export default Sa
